#include "ses_lcd.h"
#include "ses_led.h"
#include "timer/ses_timer.h"
#include "ses_adc.h"
#include "ses_uart.h"
#include "timer/ses_scheduler.h"
#include "datalogger.h"
volatile static uint16_t co2 	= 0;
volatile static uint8_t temp 	= 0;

void read_Temp(){
	//initialize the ADC
	adc_init();

	// read and convert temperature
	temp = adc_convertTemp(adc_read(ADC_TEMP_CH));

	// set the prower reduction on
	adc_disable();

	//Display temperature
	lcd_setCursor(0, 0);
	fprintf(lcdout, "temp= %d \n", temp);
	put_temperature(temp);
	scheduler_add(read_Temp,1000);
}

void read_CO2() {

	//initialize the ADC
	adc_init();

	//read CO2
	co2 = adc_read(ADC_CO2_CH) *CO2_GAIN_ERR;
	if (co2>2000)
		co2=2000;

	// set the prower reduction on
	adc_disable();

	//display CO2
	lcd_setCursor(0, 1);
	fprintf(lcdout, "co2= %4d ppm \n", co2);

	led_redOff();
	led_yellowOff();
	led_greenOff();

	if (co2 < 600) {
		led_greenOn();
	} else if (co2 >= 600 && co2 < 1000) {
		led_greenOn();
		led_yellowOn();
	} else if (co2 >= 1000 && co2 < 1400) {
		led_yellowOn();
	} else if (co2 >= 1400 && co2 < 1800) {
		led_yellowOn();
		led_redOn();
	} else if (co2 >= 1800) {
		led_redOn();
	}


	put_co2(co2);
	scheduler_add(read_CO2,1000);
}

void save(){
	save_to_eeprom();
	scheduler_add(save,5000);
}

void display_average() {
	getAverageValues();
	lcd_setCursor(0, 3);
	fprintf(lcdout, "Mean:%dC %dppm\n", DATA.avergTemp, DATA.avergCO2);
	scheduler_add(display_average, 5000);
}

int main(){

	// iniatilize phase

	lcd_init();
	lcd_clear();
	led_allInit();
	scheduler_init();
	uart_init(57600);
	fprintf(uartout, "init ...\n");
	ext_eeprom_init();
//	forceInit();
	eeprom_init();
	fprintf(uartout, "...done \n");
//
////TODO iniatlize the eeprom pointer
	scheduler_add(read_CO2,0);
	scheduler_add(read_Temp,0);
	//scheduler_add(getDataStruct,10000);
	scheduler_add(save,5000);
	scheduler_add(display_average, 0 );
	scheduler_run();

//	getDataStruct();
	while(1){};
	return 0;

}
